package com.framework.modules.common.controller;

import com.framework.common.annotation.Login;
import com.framework.common.exception.RRException;
import com.framework.common.message.MessageType;
import com.framework.common.utils.HttpContextUtils;
import com.framework.common.utils.QuickHelper;
import com.framework.common.utils.R;
import com.framework.modules.base.entity.TokenEntity;
import com.framework.modules.base.service.TokenService;
import com.framework.modules.base.service.UserInfoService;
import com.framework.modules.base.service.UserService;
import com.framework.modules.chat.entity.ChatMessageEntity;
import com.framework.modules.chat.service.ChatFriendService;
import com.framework.modules.chat.service.ChatMessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/chatapi")
@DependsOn("databaseInitConfig")
@Api(tags = "聊天服务器接口")
public class ChatServerApiController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ChatMessageService chatMessageService;

    @Autowired
    private ChatFriendService chatFriendService;

    @RequestMapping("check_token")
    @ApiOperation("用户凭证检查")
    public R check() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 从header中获取token
        String token = request.getHeader("token");
        String platform = request.getHeader("platform");
        // 如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }
        // token为空
        if (StringUtils.isBlank(token)) {
            throw new RRException("token不能为空", -101);
        }

        // 查询token信息
        TokenEntity tokenEntity = tokenService.queryByToken(token,platform);
        if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
            throw new RRException("token失效，请重新登录", -101);
        }
        return R.ok("你已登录").put("data", userInfoService.getInfo(tokenEntity.getUserId(),"info"));
    }

    @Login
    @RequestMapping("add_message_item")
    @ApiOperation("存储聊天消息")
    public R addMessageItem(@RequestBody Map<String,String> params) {
        Long uid = (Long) HttpContextUtils.getHttpServletRequestHeaderValue("uid");
        logger.info("=============== uid = %s 存储消息  =================");
        logger.info(QuickHelper.object2json(params));

        ChatMessageEntity entity = new ChatMessageEntity();
        entity.setToUid(Integer.valueOf(params.getOrDefault("to_uid","0")));
        entity.setFromUid(Integer.valueOf(params.getOrDefault("from_uid","0")));
        entity.setContent(params.get("content"));
        entity.setType(params.get("type"));
        entity.setAdddate(QuickHelper.getNowTimeStampSeconds());

        MessageType type=MessageType.valueOfName(params.get("type"));
        String content="";
        switch (type){
            case TEXT:content=params.get("content");break;
            case IMAGE:content="[图片]";break;
            case EMOJI:content="[表情]";break;
            case VOICE:content="[语音]";break;
            case LOCATION:content="[定位]";break;
            case RED_PACKET:content="[红包]";break;
            default:;
        }

        Boolean result = chatMessageService.insert(entity);
        Integer updated = chatFriendService.updateFriendBlockMessage(entity.getToUid(),entity.getFromUid(),content);
        return R.ok("存储完成").put("result",result).put("updated",updated);
    }

    @RequestMapping("check_server_info")
    @ApiOperation("存储聊天消息")
    public R check_server_info() {
        return R.ok("检查服务器信息成功");
    }
}
